package com.lwl.dubbo.controller;


import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;  
  
import com.opensymphony.xwork2.ActionSupport;
import com.lwl.dubbo.domain.Toptic;
import com.lwl.dubbo.service.ITopticService;  
  
public class UploadAction extends ActionSupport {   
      
	private static final long serialVersionUID = -8481645086167728293L;
		//上传文件存放路径   
         private final static String UPLOADDIR = "/upload";   
     	 private String forwardPage = "";
         private Toptic toptic;
     	@Resource
    	private ITopticService topticService;
             	
     	//上传文件集合   
        private List<File> file;   
        //上传文件名集合   
        private List<String> fileFileName;   
        //上传文件内容类型集合   
        private List<String> fileContentType;   
        public List<File> getFile() {   
            return file;   
        }   
 
        public void setFile(List<File> file) {   
            this.file = file;   
        }   
 
       public List<String> getFileFileName() {   
           return fileFileName;   
       }   
 
        public void setFileFileName(List<String> fileFileName) {   
            this.fileFileName = fileFileName;   
        }   
 
        public List<String> getFileContentType() {   
            return fileContentType;   
        }   
 
        public void setFileContentType(List<String> fileContentType) {   
            this.fileContentType = fileContentType;   
        }   
		public Toptic getToptic() {
			return toptic;
		}

		public void setToptic(Toptic toptic) {
			this.toptic = toptic;
		}
		
		public String getForwardPage() {
			return forwardPage;
		}

		public void setForwardPage(String forwardPage) {
			this.forwardPage = forwardPage;
		}

		public String execute() throws Exception {   
        	 HttpServletRequest request = ServletActionContext.getRequest();
     		HttpSession session2 = request.getSession();
//        	 String username = session.get("username").toString();
//     		// 获取角色：学生、老师、管理员
//     		String role = session.get("role").toString();
     		String username = (String) session2.getAttribute("username");
     		String role = (String) session2.getAttribute("role");
     		//文件
            for (int i = 0; i < file.size(); i++) {   
                //循环上传每个文件   
            	 System.out.println();  
            	toptic = uploadFile(i,toptic);   
            }                        
            
     		if (StringUtils.isNotBlank(role) && "teacher".equals(role)) {
     			  Date currentTime = new Date();
     			  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
     			  String dateString = formatter.format(currentTime);
     			String sql = "INSERT INTO toptic(topName,topDate,status,ttid,savePath,fileName) "
     					+ "VALUES('"+toptic.getTopName()+"','"+dateString+"','"+"未确认"+"','"+username+"','"+toptic.getSavePath()+"','"+toptic.getFileName()+"')";
     			
     			System.out.println(username);
     			topticService.insertBySql(sql);		
     		} else {
     			System.out.println("只有老师能发布课题...");
     		}   		
     		forwardPage = "Teacher_queryToptic.action";
    		return "forwardTchMessage";	
         }   
  
         //执行上传功能   
         private Toptic uploadFile(int i, Toptic toptic) throws FileNotFoundException, IOException {   
             try {   
                 InputStream in = new FileInputStream(file.get(i));   
//                 String dir = ServletActionContext.getRequest().getSession().getServletContext().getRealPath(UPLOADDIR);
                 //此地址自己配置
                 String dir = "F:/java upload" + UPLOADDIR;
                 if (dir != null) {
                	 dir=dir.replaceAll("\\\\", "\\\\\\\\"); 
         		}
                 toptic.setSavePath(dir);
                 File fileLocation = new File(dir);  
                 //此处也可以在应用根目录手动建立目标上传目录  
                 if(!fileLocation.exists()){  
                     boolean isCreated  = fileLocation.mkdir();  
                     if(!isCreated) {  
                         //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。  
                     }  
                 }  
                 String fileName=this.getFileFileName().get(i); 
                 toptic.setFileName(fileName);
                 File uploadFile = new File(dir, fileName);   
                 OutputStream out = new FileOutputStream(uploadFile);   
                 byte[] buffer = new byte[1024 * 1024];   
                 int length;   
                 while ((length = in.read(buffer)) > 0) {   
                     out.write(buffer, 0, length);   
                 }   
                 in.close();   
                 out.close();
                
             } catch (FileNotFoundException ex) {   
                 System.out.println("上传失败!");  
                 ex.printStackTrace();   
             } catch (IOException ex) {   
                 System.out.println("上传失败!");  
                 ex.printStackTrace();   
             }  
             return toptic;
         }   
     }